#include "Server.h"
#include "Object.h"
#include "time.h"

const float Server::CLIENT_UPDATE_TIME = .1f;

using namespace boost::asio::ip;

Server::Server(void)
{
	//registering to objct input system
	Object::setMessageHandler( this );
	Object::init(true);

	_world = NxOgre::World::createWorld();
	_timeController = NxOgre::TimeController::getSingleton();
	NxOgre::SceneDescription _descrptn;
	_descrptn.mName = " Andi is sooooooo cool ";
	_descrptn.mGravity = NxOgre::Vec3( 0, -10.3f, 0 );

    _scene = _world->createScene( _descrptn );

	//create Scene
	NxOgre::ResourceSystem::getSingleton()->openArchive( "NXS", "file:../../media/models" );

	NxOgre::Shapes _s;
	NxOgre::Box* _box = new NxOgre::Box( 20,20,1 );
	_box->setLocalPose( NxOgre::Matrix44( NxOgre::Vec3( 0, 0, 10 ) ));
	_s.insert( _box );
	_box = new NxOgre::Box( 20,20,1 );
	_box->setLocalPose( NxOgre::Matrix44( NxOgre::Vec3( 0, 0, -10 ) ));
	_s.insert( _box );
	_box = new NxOgre::Box( 1,20,20 );
	_box->setLocalPose( NxOgre::Matrix44( NxOgre::Vec3( -10, 0, 0 ) ));
	_s.insert( _box );
	_box = new NxOgre::Box( 1,20,20 );
	_box->setLocalPose( NxOgre::Matrix44( NxOgre::Vec3( 10, 0, 0 ) ));
	_s.insert( _box );

	_scene->createKinematicActor( _s );
	_scene->createSceneGeometry( new NxOgre::PlaneGeometry( 0, NxOgre::Vec3( 0, 1, 0) ), Matrix44_Identity );

	//connect visual debbugger
	NxOgre::RemoteDebugger *pRD = _world->getRemoteDebugger();
		pRD->connect();

}

//----------------------------------------------->

Server::~Server(void)
{
}

//----------------------------------------------->

void Server::onReceivePlayerMessage(PlayerMessage *receivedMessage,boost::asio::ip::udp::endpoint senderEndpoint)
{
	// not needed by server
}
void Server::onReceiveItemMessage(ItemMessage *receivedMessage,boost::asio::ip::udp::endpoint senderEndpoint)
{
	// note needed by server
}

void Server::onReceiveControlMessage(ControlMessage *receivedMessage,boost::asio::ip::udp::endpoint senderEndpoint)
{
	if ( _playerMap[senderEndpoint]._control == NULL )
	{
		//std::cout << "New player at: " << senderEndpoint << "\n";
		PlayerMessage *object = Object::createPlayerMessage( receivedMessage->_id._machine );
		_playerMap[ senderEndpoint ] = Player( this, senderEndpoint, receivedMessage, object);
		Network::addReceiverEndpoint( senderEndpoint );
	} 
}

void Server::updatePhysics(float dt)
{
	_timeController->advance( dt );
}

NxOgre::Scene* Server::getNxScene()
{
	return _scene;
};